<?php

declare(strict_types=1);

namespace App\AdminApi\Modular\Data\Controller;

use App\AdminApi\BasicsController;
use App\AdminApi\Modular\Data\Service\RegionService;
use App\Common\Extend\Guard\Auth;
use Core\HyperfUnit\Response;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\{
    Controller,
    GetMapping,
    PostMapping
};
use Psr\Http\Message\ResponseInterface;
use Zms\HyperfValidateAnnotations\Validate;

#[
    Controller(prefix: "/admin-api/data-region", server: self::SERVER),
    Auth(guard: self::GUARD, label: ['数据管理', '行政地区'], app: self::APP)
]
class RegionController extends BasicsController
{
    #[Inject]
    protected RegionService $service;


    #[
        GetMapping('list'),
        Auth(sign: "data.region", view: '/data/region/index')
    ]
    public function list(): ResponseInterface
    {
        $where = $this->request->inputs(['pid', 'name'], ['pid' => 0]);
        $data = $this->service->search($where)->get()->toArray();
        return Response::Api()->success(data: $data);
    }

    #[
        PostMapping('change-hot'),
        Auth(label: ['设置热门地区'], sign: "data.region.change-hot"),
        Validate(rules: [
            [['id', 'state'], 'required', 'error' => '数据异常,请刷新重试'],
            ['state', 'in', 'enums' => ['0', '1'], 'error' => '数据异常,请刷新重试']
        ])
    ]
    public function changeHot(): ResponseInterface
    {
        $data = $this->request->getParsedBody();
        if ($this->service->search(['id' => $data['id']])->update(['is_hot' => $data['state']])) {
            return Response::Api()->success('设置成功');
        }
        return Response::Api()->fail('设置失败');
    }
}